<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改疾病管理')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
</head>
<style type="text/css">
    *{margin:0;padding:0;list-style-type:none;}
    a,img{border:0;}
    body{background:#333;}

    .words-split{vertical-align: middle;}
    .lbl-input{
        display: inline-block;width: 120px; height: 26px;
        line-height: 26px;
        min-height: 26px;
        text-indent: 1em;
        border: 1px solid #ddd; border-radius: 5px;
        color:#002530;
        vertical-align: middle;
    }
    .words-split a{display: inline-block; padding:0 20px 0 8px; position: relative; margin:0 4px; }
    .words-split a em{display:none; width: 16px; height: 100%; position: absolute; background: #f60;right: 0;top: 0;}
    .words-split a em:after{ content: "-"; color: #fff; font: bold 20px 'Microsoft Yahei';}
    .words-split a:hover em{ display: block; }
    a.words-split-add{display: inline-block;font: bold 20px 'Microsoft Yahei'; color: #2cac93}

    .fm-button {
        display: inline-block;
        text-align: center;
        color: #fff;
        height: 28px;
        line-height: 28px;
        font-size: 14px;
        padding: 0 1em;
        border-radius: 3px;
        opacity: .9;
        filter: alpha(opacity=90);
        background:#2cac93;
    }
    a{text-decoration:none;}
    h3{color: #002530}
</style>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-disease-edit" th:object="${disease}">
        <input name="id" th:field="*{id}" type="hidden">

        <div class="tab-content">
            <div class="form-group">
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">父级科目</label>
                    <div class="col-sm-10">
                        <div class="input-group">
                            <input id="treeId" name="pid" type="hidden" th:field="*{pid}"/>
                            <input class="form-control" placeholder="请选择父级疾病" type="text" th:field="*{parentName}" onclick="selectDiseaseTree()" id="treeName" readonly="true" th:value="${disease?.name}">
                            <span class="input-group-addon"><i class="fa fa-search"></i></span>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label is-required">英文名称</label>
                    <div class="col-sm-10">
                        <input name="nameEn" id="nameEn"  th:field="*{nameEn}" class="form-control" placeholder="请输入英文名称" type="text" required>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">中文名称</label>
                    <div class="col-sm-10">
                        <input name="name" id="name"  class="form-control" th:value="*{name}" placeholder="请输入中文名称" type="text">
                    </div>
                </div>
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">排序</label>
                    <div class="col-sm-10">
                        <input name="sortid"  th:field="*{sortid}" class="form-control" placeholder="请输入排序数字" type="text">
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-1 control-label">药品描述</label>
                <div class="col-sm-11">
                        <textarea name="drugD" class="form-control"  th:field="*{drugD}" placeholder="请输入描述" type="text">
                        </textarea>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">标题</label>
                    <div class="col-sm-10">
                        <input name="drugT" class="form-control" th:value="*{drugT}" placeholder="请输入标题" type="text">
                    </div>
                </div>
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">关键词</label>
                    <div class="col-sm-10">
                        <input name="drugK" class="form-control"  th:field="*{drugK}" placeholder="请输入关键词" type="text">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">靶点</label>
                <div class="col-sm-11">
                    <input type="text" name="staticPath"   id="staticPath" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">药品内容:</label>
                <div class="col-sm-11">
                    <input type="hidden" class="form-control" required>
                    <script id="drugDescribe" th:field="*{drugD}"  name="drugDescribe" type="text/plain"></script>
                </div>
            </div>
            <div class="form-group" id="flagShow">
                <label class="col-sm-1 control-label">临床内容:</label>
                <div class="col-sm-11">
                    <input type="hidden" class="form-control" required>
                    <script id="lcDescribe" th:field="*{lcDescribe}" name="lcDescribe" type="text/plain"></script>
                </div>
            </div>

        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<script src="/ueditor/ueditor.config.js" type="text/javascript" charset="utf-8"></script>
<script src="/ueditor/ueditor.all.js" type="text/javascript" charset="utf-8"></script>
<script src="/ueditor/lang/zh-cn/zh-cn.js" type="text/javascript" charset="utf-8"></script>
<script th:inline="javascript">
    let diseaseTarget = [[${disease}]].diseaseTarget;

    var prefix = ctx + "new/disease";
    $("#form-disease-edit").validate({
        focusCleanup: true
    });
    $(document).ready(function () {
        parent.$('body').find('.layui-layer-max:not(.layui-layer-maxmin)').click()
        //组装标签
        var staticPath = "";
        diseaseTarget.forEach(item => {
            staticPath += item.name + ',';
        });
        $('#staticPath').val(staticPath.slice(0, -1));
        WS({el:'#staticPath'});
        if(null != diseaseTarget){
            document.getElementById('flagShow').style.display = 'none';
        }
    });

    function submitHandler() {
        var jsons = {};
        if ($.validate.form()) {
            if('' == $('#name').val()){
                $.modal.alertError("请填写【基本信息】中的疾病名称！");
                return
            }
            debugger
            var staticPath = $('#staticPath').val();
            var arr = staticPath.split(',');
            // 创建对象集合，集合中的每个对象都包含一个键为 'name' 的属性
            var objSet = arr.map(item => ({ name: item }));
            // 通过name键合并两个数组中的相同name的对象
            const mergedArray = diseaseTarget.map(item1 => {
                // 查找objSet中name相同的元素
                const match = objSet.find(item2 => item2.name === item1.name);
                if (match) {
                    // 如果有相同name的对象，则合并两个对象
                    return { ...item1, ...match };
                }
                return item1;  // 没有匹配项则返回原来的对象
            }).concat(objSet.filter(item2 =>
                !diseaseTarget.some(item1 => item1.name === item2.name)
            ));

            let formData = $('#form-disease-edit').serializeArray()
            $.each(formData, function (k, v) {
                jsons[v.name] = v.value;
            });
            jsons['diseaseTarget']=mergedArray
            var jsonvalue = JSON.stringify(jsons)
            save(prefix + "/edit", jsonvalue);
        }
    }

    //json请求
    function save(url, data, callback) {
        var config = {
            url: url,
            type: "post",
            dataType: "json",
            data: data,
            headers: {
                'Content-Type': 'application/json;charset=utf8'
            },
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍候...");
                $.modal.disable();
            },
            success: function (result) {
                if (typeof callback == "function") {
                    callback(result);
                }
                $.operate.successCallback(result);
            }
        };
        $.ajax(config)
    }

    $(".file-upload").each(function (i) {
        var val = $("input[name='" + this.id + "']").val()
        if (val==""){
            $(".file-upload").fileinput({
                uploadUrl: ctx + 'common/upload',
                maxFileCount: 1,
                autoReplace: true
            }).on('fileuploaded', function (event, data, previewId, index) {
                $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName)
            }).on('fileremoved', function (event, id, index) {
                $("input[name='" + event.currentTarget.id + "']").val('')
            })
        }else{
            $(this).fileinput({
                'uploadUrl': ctx + 'common/upload',
                initialPreviewAsData: true,
                initialPreview: [val],
                maxFileCount: 1,
                autoReplace: true
            }).on('fileuploaded', function (event, data, previewId, index) {
                $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName)
            }).on('fileremoved', function (event, id, index) {
                $("input[name='" + event.currentTarget.id + "']").val('')
            })
            $(this).fileinput('_initFileActions');
        }
    });

    /*疾病管理-编辑-选择父疾病管理树*/
    function selectDiseaseTree() {
        var options = {
            title: '疾病管理选择',
            width: "480",
            url: prefix + "/selectDiseaseTree/" + $("#treeId").val(),
            callBack: doSubmit
        };
        $.modal.openOptions(options);
    }

    function doSubmit(index, layero) {
        var body = $.modal.getChildFrame(index);
        $("#treeId").val(body.find('#treeId').val());
        $("#treeName").val(body.find('#treeName').val());
        $.modal.close(index);
    }

    //富文本
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function (action) {
        if (action == 'uploadimage' || action == 'uploadscrawl') {
            return '/common/upload';
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }
    var due = UE.getEditor('drugDescribe', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });
    due.ready(function () {
        due.execCommand("insertHtml", [[${disease}]].drugDescribe);//富文本回显
    })
    var lue = UE.getEditor('lcDescribe', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });
    lue.ready(function () {
        lue.execCommand("insertHtml", [[${disease}]].lcDescribe);//富文本回显
    })

</script>
<script type="text/javascript">
    var WS = function(opt){

        var regexp = opt.regexp || /\S/,
            el = $(opt.el),
            list = el.val().split(','),
            holder = $('<span class="words-split"></span>'),
            add = $('<a href="javascript:void(0)" class="words-split-add">+</a>');



        for (var i = 0; i < list.length; i++) {
            if("" == list[i]){
                continue;
            }
            holder.append( $('<a href="javascript:void(0)" class="fm-button">'+list[i]+'<em> </em></a>') );
        }

        el.hide().after( holder );
        holder.after(add);

        holder.on('click','a>em',function(){	//刪除
            $(this).parent().remove();
            //获取删除的元素名称
            var targetKey = $(this).parent().text().trim();
            //查找回显集合中的元素，有则更改有效性，没有则忽略
            const target = diseaseTarget.find(item => item.name === targetKey);
            if (target) {
                target.delFlag = "1";  // 修改有效性为1,（无效，用作删除）
            }
            //当标签为空时，显示临床html编辑框
            if(null != holder.text().match(/\S+/g)){
                el.val( holder.text().match(/\S+/g).join(',') )
            }else{
                document.getElementById('flagShow').style.display = 'block';
            }
        });

        add.on('click',function(){				//添加预处理
            $(this).hide();
            holder.append( $('<span class="lbl-input" contenteditable="true"/>') )
        });

        holder.on('blur','.lbl-input',function(){	//验证添加字段
            debugger
            var t = $(this),v = t.text();
            if( regexp.test(v) ){
                t.remove();
                add.show();
                holder.append( $('<a href="javascript:void(0)" class="fm-button">'+v+'<em> </em></a>') );
                el.val( holder.text().match(/\S+/g).join(',') )
                //验证添加标签时，隐藏html编辑框
                if(null != holder.text().match(/\S+/g)){
                    document.getElementById('flagShow').style.display = 'none';
                }
            }else if(!v){
                t.remove();
                add.show();
            }else{
                alert('输入不合法');
            }
        });

        holder.on('keydown','.lbl-input',function(e){
            switch(e.keyCode){
                case 13:
                case 27: $(this).trigger('blur');
            }
        });

    }


</script>
</body>
</html>